<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Requests\BasicRequest;
use App\Jobs\RongcloudHistory;
use App\Libraries\msg\Push;
use App\Libraries\rong_cloud_sdk\Rongyun;
use App\Models\ApiBehavior;
use App\Models\Area;
use App\Models\ClientUser;
use App\Models\ClientUserHouse;
use App\Models\House;
use App\Models\ClientUserIntegral;
use App\Models\ClientUserRelationship;
use App\Models\Config;
use App\Models\HouseDistrict;
use App\Models\HouseDistrictCar;
use App\Models\HouseDistrictCosts;
use App\Models\HouseDistrictOwner;
use App\Models\ClientUserManagerWork;
use App\Models\NeighborCouncilComplaints;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Mockery\Exception;
use Psr\Log\InvalidArgumentException;
use App\Models\Message;
//use App\Libraries\AipSpeech;
//
//const APP_ID = '10528921';
//const API_KEY = 'FySU1YjHWmMTqYWbiPXZtbKy';
//const SECRET_KEY = 'f63412ff7ad3f764ddcc40ee4d66516c';
class SandboxController extends CommonController
{

	public function test(BasicRequest $request){
        //Message::message_push(27,'new_order','您有一条新订单待发货，订单号：123,请及时处理,123','123',1);
        //set_time_limit(0);
		//$this->change_house_sn();
//		$rongyun = new Rongyun();
//          set_time_limit(0);
          //ignore_user_abort(true);
          //$this->_import_house();
          //$this->add_house();
		  //$this->edit_xtyn();
		  //$this->import_money();

//		$ls = $rongyun->message()->publishPrivate('1','4','RC:TxtMsg',json_encode($content),'','','0','0','1','1','0');
		// array:1 [▼
		// 		"code" => 200
		// ]
//		$rongcloudHistory = new RongcloudHistory();
//		logger('sdfjklsdjfklsjkl ');
//		dispatch($rongcloudHistory->onQueue('rongcloud'));
		// 内部使用 artisan 命令
//		Artisan::call('optimize',['--queue'=>1]);
//		$s = collect([['name'=>'dfdf'],['name'=>'dfdfdd']])->where('name','dfdf')->all();
//		$s = ApiBehavior::first();
//		$s->detail();
//		return $s;
//		\Storage::disk('public')->put('avatar.png',file_get_contents('./images/avatar.png'));
//		$s = \Storage::disk('public')->size('avatar.png');
//		dd($s);
//		$app = new App();
//		$sign = $app->wechat(rand(100000,999999),'慧生活',0.01,'http://www.qiuxingren.com/sss');
//		dd($sign);
//		send_message('17099912460','验证码',['8888','30']);
//		HouseDistrict::where('parent_id',0)->get()->each(function($v,$k){
//			HouseDistrict::where('parent_id',$v->id)->get()->each(function($v,$k){
//				$str = str_pad(substr($v->name,0,1),2,'0',STR_PAD_LEFT);
//				$v->sn = $str;
//				$v->save();
//				HouseDistrict::where('parent_id',$v->id)->get()->each(function($v,$k) use (&$str){
////					$str .= str_pad(intval($v->name),2,'0',STR_PAD_LEFT);
//					$str2 = $str . str_pad(intval($v->name),2,'0',STR_PAD_LEFT);
//					$v->sn = $str2;
//					$v->save();
//					HouseDistrict::where('parent_id',$v->id)->get()->each(function($v,$k) use (&$str2){
////						$str .= str_pad(intval($v->name),2,'0',STR_PAD_LEFT);
//						$str3 = $str2 . str_pad(intval($v->name),2,'0',STR_PAD_LEFT);
//						$v->sn = $str3;
//						$v->save();
//						HouseDistrict::where('parent_id',$v->id)->get()->each(function($v,$k) use (&$str3){
////							$str .= str_pad(intval($v->name),2,'0',STR_PAD_LEFT);
//							$str4 = $str3 . str_pad(intval(substr($v->name,2)),2,'0',STR_PAD_LEFT);
//							$v->sn = $str4;
//							$v->save();
//						});
//					});
//				});
//			});
//		});


	}
	
	private function change_house_sn(){
	    $house = House::where(['village_id'=>9259])->where('id','>',979)->get()->each(function($v,$k){
	       $house_sn = $v->house_sn;
	       $house_sn_new = '';
	       for ($i=0;$i<strlen($house_sn);$i++){
	           switch ($i) {
                   case 0:
                           $house_sn_new .= $house_sn[$i];
                       break;
                   case 1:
                       if($house_sn[$i]!=0){
                           $house_sn_new .= $house_sn[$i];
                       }
                       break;
                   case 2:
                        $house_sn_new .= $house_sn[$i].'-';
                        break;
                   case 4:
                       $house_sn_new .= $house_sn[$i].'-';
                       break;
                   case 5:
                   case 6:
                   case 7:
                   case 8:
                       $house_sn_new.= $house_sn[$i];
                        break;

               }

            }
           House::where('id',$v->id)->update(['house_sn'=>$house_sn_new]);
        });
    }
	private function edit_xtyn(){
		$house=House::where(['village_id'=>7202])->get()->each(function($v,$k){
			$house_id=$v->house_id;
			$floor_id = HouseDistrict::where(['id'=>$house_id])->value('parent_id');
			House::where(['house_id'=>$house_id])->update(['floor_id'=>$floor_id]);
		});
		
	}
	private function import_work(){
        $file = fopen('./yupeng.csv','r+');

        $i = 0;
        while($line = fgetcsv($file)) {
            $i++;
            if ($i <= 1) {
                continue;
            }
            foreach($line as $k => $v){
                $line[$k] = trim(iconv('gbk','utf-8',$line[$k]));
            }
            $work=[];
            $work['work'] = $line[0]. chr(10).$line[1]. chr(10).$line[2];
            $work['house_id'] = 9259;
            $work['uid'] = 2465;
            $work['work_remarks'] = $line[3];
            $work['created_at'] = date('Y-m-d H:i:s');
            $work['updated_at'] = date('Y-m-d H:i:s');

            $return=ClientUserManagerWork::create($work);

        }

    }

	private function _import_house(){
		$file = fopen('./test1.csv','r+');

		$i = 0;
		$house_in = [];
		while($line = fgetcsv($file)){
			$i++;
			if($i <= 1){
				continue;
			}
			foreach($line as $k => $v){
				$line[$k] = trim(iconv('gbk','utf-8',$line[$k]));
			}

			$houses = [];
			$houses[] = $line[0];
			$houses[] = $line[1];
			$houses[] = $line[2].'栋';
			$houses[] = $line[3].'单元';
			$houses[] = $line[4].'层';
			$houses[] = '0'.$line[5].'号';

			$house_unique_name = $houses[0].'_'.$houses[1].'_'.$houses[2].'_'.$houses[3].'_'.$houses[4].'_'.$houses[5];
               $mobile=$line[11];
               $bulid_area = $line[6];
               $use_area = $line[10];
               $car = $line[12];

               $data = ['build_area'=>$bulid_area,'use_area'=>$use_area,'owner_mobile'=>$mobile,'car'=>$car,'realname' => $line[7]];
               if($line[8]) {
                    $data['username'] = $line[8];
                    $data['password'] = md5($line[9]);
                    $data['user_mobile'] =$line[13];
               }
			$house_unique[$house_unique_name] = $data;

			// 插入房屋数据
			$house_names = explode('_',$house_unique_name);

			$unique2 = [];
			foreach($house_names as $house_name){
				// 之前的数据拼接存数组，数组键作为唯一值筛选
				$unique2[] = $house_name;
				$unique2_implode = implode('_',$unique2);
				if(substr_count($unique2_implode,'_') == 5){
					$house_in[$unique2_implode] = $data;
				}else{
					$house_in[$unique2_implode] = [];
				}
			}

		}

		ksort($house_in);
		$house_insert_history = [];
          DB::beginTransaction();
          foreach($house_in as $house => $data){
                    if (empty($house) || ($house == '哈尔滨市群力新城小区')) {
                         continue;
                    }

                    $house_explode = explode('_', $house);
                    $type = count($house_explode);
                    if ($type == 2) {
                         $type = 7;
                    }

                    $house_name = array_pop($house_explode);
                    $house_implode_parent = implode('_', $house_explode);
                    $parent_id = $house_insert_history[$house_implode_parent] ?? 9259;

                    $house_add = [
                        'parent_id' => $parent_id,
                        'name' => $house_name,
                        'build_area' => $data['build_area'] ?? '',
                        'use_area' => $data['use_area'] ?? '',
                        'status' => 1,
                        'type' => $type
                    ];

                    $house_id = HouseDistrict::create($house_add)->id;
                    $house_insert_history[$house] = $house_id;

                    if ($data['car']) {
                         $car_add = [
                             'house_id' => $house_id,
                             'name' => $data['car'],
                         ];
                         HouseDistrictCar::create($car_add);
                    }
                    if ($data['owner_mobile']) {
                         // 处理业主等数据
                         $house_owner_add = [
                             'house_id' => $house_id,
                             'realname' => $data['realname'] ?? '',
                             'mobile' => $data['owner_mobile'] ?? '',
                             'if_primary' => 1,
                         ];
                         HouseDistrictOwner::create($house_owner_add);
                    }
                    if ($data['username']) {

                         //处理用户数据
                         $user = array(
                             'username' => $data['username'],
                             'realname' => $data['realname'],
                             'mobile' => $data['user_mobile'],
                             'password' => $data['password'],
                             'type' => 1,
                             'status' => 1,
                             'gender' => 1
                         );

                         $check = ClientUser::where(['mobile' => $data['user_mobile']])->first();
                         $check1 = ClientUser::where(['username' => $data['username']])->first();
                         if ($check) {
                              $user_id = $check['id'];
                         }else if ($check1) {
                              $user['username'] = $data['username'] . 'x';
                              $user_id = ClientUser::create($user)->id;
                         } else {
                              $user_id = ClientUser::create($user)->id;
                         }
                         $user_house = array(
                             'uid' => $user_id,
                             'primary' => 1,
                             'house_id' => $house_id,
                             'village_id' => 9259
                         );
                         ClientUserHouse::create($user_house);
                         if ($house_id) {
                              $house = array(
                                  'house_id' => $house_id,
                                  'create_time' => date('Y-m-d H:i:s'),
                                  'status' => 0,
                              );
                              House::insert($house);
                         }
                    }
                     $this->add_house();
               }

          DB::commit();
          fclose($file);
	}
	private function import_money(){
		$file = fopen('./test1.csv','r+');
		$i = 0;
		$house_in = [];
		while($line = fgetcsv($file)){
			$i++;
			if($i <= 1){
				continue;
			}
			foreach($line as $k => $v){
				$line[$k] = trim(iconv('gbk','utf-8',$line[$k]));
			}
			$houses = [];

			$houses[] = $line[1];
			$houses[] = $line[2].'栋';
			$houses[] = mb_substr($line[3],-2,2).'单元';
			$houses[] = $line[4].'层';
			$houses[] = '0'.$line[5].'号';
			
			$parent_id=9259;
			foreach ($houses as $key=>$val){
                $parent_id=DB::table('house_district')->where(['parent_id'=>$parent_id,'name'=>$val])->select('id')->first()->id;
			}
			$house_id=$parent_id;
            $end_time=strtotime((date('Y',time())+1).'-01-01 00:00:00');
			$insert_wuye=array(
                'house_id'=>$parent_id,
                'type'=>1,
                'type_name'=>'物业费',
                'start_time'=>time(),
                'end_time'=>$end_time,
                'description'=>'2017年物业年费',
                'amount'=>$line['18'],
                'status'=>1,
                'pay_status'=>1,
                'created_at'=>date('Y-m-d H:i:s',time()),
                'updated_at'=>date('Y-m-d H:i:s',time()),
            );

            $insert_dianti=array(
                'house_id'=>$parent_id,
                'type'=>1,
                'type_name'=>'电梯费',
                'start_time'=>time(),
                'end_time'=>$end_time,
                'description'=>'2017年电梯年费',
                'amount'=>intval($line['22']),
                'status'=>1,
                'pay_status'=>1,
                'created_at'=>date('Y-m-d H:i:s',time()),
                'updated_at'=>date('Y-m-d H:i:s',time()),

            );
            $insert_chewei=array(
                'house_id'=>$parent_id,
                'type'=>1,
                'type_name'=>'车位费',
                'start_time'=>time(),
                'end_time'=>$end_time,
                'description'=>'2017年车位年费',
                'amount'=>intval($line['14']),
                'status'=>1,
                'pay_status'=>1,
                'created_at'=>date('Y-m-d H:i:s',time()),
                'updated_at'=>date('Y-m-d H:i:s',time()),
            );
            if($line['19']=='是'){
                $insert_wuye['pay_status']=0;
            }
            if($line['15']=='是'){
                $insert_chewei['pay_status']=0;
            }
            if($line['23']=='是'){
                $insert_dianti['pay_status']=0;
            }
            HouseDistrictCosts::insert($insert_chewei);
            HouseDistrictCosts::insert($insert_dianti);
            HouseDistrictCosts::insert($insert_wuye);
		};
		fclose($file);
	}
	public function _house_son($parent_id,$name){
		
		
	}
	public function index(){
		return view('sandbox.index');
	}
     public function add_house(){
          $houseClass= new HouseDistrict();
          DB::table('house')->where(['status'=>2])->where('id','<','3340')->where('id','>=','2460')->select('house_id')->get()->each(function($val,$k) use($houseClass){

               $id=$val->house_id;
               $update = array(
//                   'create_time' => date('Y-m-d H:i:s'),
                   'update_time' => date('Y-m-d H:i:s'),
//                   'status' => 2,
               );
               $house_list = $houseClass->parent($id);
               //$update['house_detail'] = $house_list->reverse()->values()->pluck('name')->implode('');
               $house_list->reverse()->slice(1)->each(function($v,$k) use (&$update){
                        if($v->type==5){

                        }else if($v->type==6){
                             $no = str_pad(intval($v->name), 4, '0', STR_PAD_LEFT);
                             $update['house_sn'] .= $no;
                        }else if($v->type>=3 && intval($v->name)>0) {
                              $no = str_pad(intval($v->name), 2, '0', STR_PAD_LEFT);
                              $update['house_sn'] .= $no;
                         }

               });
//               foreach ($house_list as $v) {
//                       if($v->type ==4){
//                            $update['unit_id']=$v->id;
//                       }
//                    if ($v->type == 2) {
//                         $update['village_id'] = $v->id;
//                         $update['area_id'] = $v->area_id;
//                         $update['city_id'] = $v->city_id;
//                         $update['province_id'] = $v->province_id;
//                    } else if ($v->type == 3) {
//                         $update['budding_id'] = $v->id;
//                    } else if ($v->type == 7) {
//                         $update['partition_id'] = $v->id;
//                    } else if($v->type == 5){
//                         $update['floor_id'] = $v->id;
//                    }
//               };
               DB::table('house')->where(['house_id' => $id])->update($update);
          });
     }
	public function submit(BasicRequest $request){

		$post = $request->except(['s']);
		$keys = $post['key'];
		$value = $post['value'];
		$curl_data = [];
		unset($post['key'],$post['value']);
		foreach($keys as $k=>$v){
			if(empty($v)) continue;
			$post[$v] = $value[$k];
		}
		$data = $post;
		unset($data['sign']);
		ksort($data);
		$str = '';
		foreach($data as $k=>$v){
			if($v === null){
				continue;
			}
			$str .= $k . '=' . $v . "&";
			$curl_data[$k] = $v;
		}
		$str = substr($str , 0 , -1);
		$sign = $post['sign'] = md5($str);	// sign 算法
		$curl_data['sign'] = $sign;
		$this->script_log('生成sign：'.$sign);
		// 设置sign
		$this->script_sign($sign);
		echo '发送的参数：';
		print_r($post);
		// 执行请求
		$sJson = $this->curlpost($curl_data);
		echo "\n".'返回源JSON：';
		print_r($sJson);

		$json = json_decode($sJson,true);
		echo "\n".'格式化JSON：';
		print_r($json);

		// 设置 token
		if($post['_cmd'] == 'user_login') $this->script_token($json['data']['ticket']);
	}

	private function script_log($log){
		$date = date('Y-m-d H:i:s');
		echo '<script type="text/javascript">log("'.$log.'----'.$date.'");</script>';
	}

	private function script_sign($sign){
		echo '<script type="text/javascript">sign("'.$sign.'");</script>';
	}
	private function script_token($ticket){
		echo '<script type="text/javascript">ticket("'.$ticket.'");</script>';
	}

	public function curlpost($array){
//		$post = http_build_query($array);
//		$_cmd = $array['_cmd'];
//		$controller = ucfirst(strstr($_cmd, '_', true));
//		$action = substr(strstr($_cmd, '_'), 1);
//		return redirect()->action($controller . 'Controller@' . $action, $array);
		$s = curl_post('http://'.request()->server('HTTP_HOST'),$array);
		return $s;


//		$post = http_build_query($array);
//		$ch = curl_init();
//
//		$url = $_SERVER['HTTP_HOST'];
//		curl_setopt($ch, CURLOPT_URL, $url);
////		curl_setopt($ch, CURLOPT_PORT, '5000');
//		curl_setopt($ch, CURLOPT_POST, 1);
//		curl_setopt($ch, CURLOPT_HEADER, 0);
//		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
//		$data = curl_exec($ch);
//		curl_close($ch);
//		return $data;
	}
}
